from flask import make_response, Flask
from flask_cors import CORS
import psycopg2
import json
import base64
import pickle

conn = psycopg2.connect(database="ether", user="postgres",password="postgres", host="127.0.0.1", port="5432")
cursor = conn.cursor()
sql = "select * from transaction"
app = Flask(__name__)
CORS(app, supports_credentials=True)
@app.route('/transactions')
def get_transactions():
    cursor.execute(sql)
    records = cursor.fetchall()
    result = {'transactions':[]}
    for record in records:
        transaction = {}
        transaction['from'] = record[1]
        transaction['to'] = record[2]
        transaction['vin'] = record[3]
        transaction['file'] = record[4]
        transaction['record_num'] = record[5]
        transaction['location'] = record[6]
        transaction['date_from'] = record[7].strftime('%Y-%m-%d %H:%M:%S')  
        transaction['date_to'] = record[8].strftime('%Y-%m-%d %H:%M:%S')  
        transaction['description'] = record[9]
        transaction['contract'] = record[10]
        transaction['price'] = record[11]
        rawdata = pickle.loads(base64.b64decode(record[12]))
        rawdata_dict = {}
        for key in rawdata:
            value = rawdata[key]
            if key in ['blockHash', 'hash', 'r', 's']:
                value = value.hex()
            rawdata_dict[key] = value
        transaction['rawdata'] = rawdata_dict
        transaction['status'] = record[13]
        transaction['password'] = record[14]
        transaction['review'] = record[15]
        result['transactions'].append(transaction)
    response = make_response(json.dumps(result))
    return response
